package krt.wid.gslzs.activity;


import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

//import com.airsaid.pickerviewlibrary.OptionsPickerView;
import com.bigkoo.pickerview.OptionsPickerView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Response;

import java.util.ArrayList;
import java.util.List;

import krt.wid.gslzs.adpater.ImagePickerAdapter;
import krt.wid.gslzs.bean.AppealBean;
import krt.wid.gslzs.bean.Choose_BM;
import krt.wid.gslzs.R;
import krt.wid.gslzs.base.BaseActivity;
import krt.wid.gslzs.bean.UploadBean;
import krt.wid.gslzs.bean.UserInfo;
import krt.wid.gslzs.util.AppealDialog;
import krt.wid.gslzs.util.SelectDialog;
import krt.wid.http.MHttp;
import krt.wid.http.MResponseListener;
import krt.wid.http.Result;
import krt.wid.http.upload.MUpload;
import krt.wid.inter.UploadCallBack;
import krt.wid.util.MToast;
import krt.wid.util.ParseJsonUtil;
import krt.wid.gslzs.util.CommomDialog;
import krt.wid.gslzs.util.GlideImageLoader;
import krt.wid.gslzs.util.GlideUtil;
import krt.wid.gslzs.util.SureDiagle;
import krt.wid.gslzs.util.TitleManager;

/**
 * @author admin
 * @date 2018/5/8
 * 诉求提交
 */

public class AppealActivity extends BaseActivity implements View.OnClickListener, ImagePickerAdapter.OnRecyclerViewItemClickListener {

    FrameLayout leftLayout;
    TextView appeal_name;
    TextView appeal_type;
    TextView appeal_bumen;
    ImageView photo_image;
    Button sb_confirm;
    EditText order_content;

    //上传或者选中照片的地址
    String path;

    String accesstoken;
    String UserXx;
    //获取照片地址
    String url1 = "";
    String uuid;
    String region;
    String regionName;


    List<Choose_BM> bmlist = new ArrayList<Choose_BM>();

    private List<AppealBean.DataBean> aList = new ArrayList<>(); //诉求类型选择

    //多张上传
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    private ImagePickerAdapter adapter;
    private ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 9;               //允许选择图片最大数

    @Override
    public int bindLayout() {
        return R.layout.activity_appeal;
    }

    @Override
    public void initView() {

        //最好放到 Application oncreate执行
        initImagePicker();
        initWidget();

        //获取缓存token
        UserInfo userInfo = mSpUtil.getUserInfo();
        if (userInfo != null) {
            accesstoken = mSpUtil.getAccessToken();
            UserXx = userInfo.getEnterprise().getEname().toString();
            uuid = userInfo.getUuid();
            region = userInfo.getRegion();
            regionName = userInfo.getEnterprise().getRegionName();
        }
        //设置标题栏
        TitleManager titleManager = new TitleManager(this);
        titleManager.hideDivider();
        titleManager.setCenterText("诉求提交", ContextCompat.getColor(this, R.color.white), 18);

        leftLayout = findViewById(R.id.left_layout);
        sb_confirm = findViewById(R.id.sb_confirm);
        appeal_name = findViewById(R.id.appeal_name);
        order_content = findViewById(R.id.order_content);

        appeal_name.setText(UserXx);

        //诉求类别
        appeal_type = findViewById(R.id.appeal_type);
        appeal_bumen = findViewById(R.id.appeal_bumen);
        leftLayout.setOnClickListener(this);
        appeal_type.setOnClickListener(this);
        appeal_bumen.setOnClickListener(this);
        sb_confirm.setOnClickListener(this);


        //   诉求页获取部门
        String url = "http://111.75.240.74:13381/non_public_economy/api/depList";
        MHttp.<Result<List<Choose_BM>>>create(AppealActivity.this).setUrl(url)
                .addParams("accessToken", accesstoken)
//                .addParams("depType","2")
                .setMethod(RequestMethod.GET)
                .execute(new MResponseListener<Result<List<Choose_BM>>>() {
                    @Override
                    public void onSuccess(int what, Result<List<Choose_BM>> bumen_type) {
                        if (bumen_type.isSuccess()) {
                            bmlist.addAll(bumen_type.getData());
                            Log.w("zxccc", ParseJsonUtil.toJson(bumen_type));

                        } else {
                            MToast.showToast(AppealActivity.this, bumen_type.getMsg());
                        }


                    }

                    @Override
                    public void onFailed(int what, Response<Result<List<Choose_BM>>> response) {

                    }
                });
    }


    @Override
    public void loadData() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.left_layout:
                finish();
                overridePendingTransition(R.anim.in2, R.anim.out2);
                break;

            case R.id.appeal_type:
                String url = "http://111.75.240.74:13381/non_public_economy/api/appealTypeCount";
                MHttp.<AppealBean>create(this)
                        .setUrl(url)
                        .addParams("accessToken", accesstoken)
                        .setMethod(RequestMethod.GET)
                        .execute(new MResponseListener<AppealBean>() {
                            @Override
                            public void onSuccess(int what, AppealBean appealBean) {
                                if (appealBean.getCode() == 0) {
                                    aList = appealBean.getData();
                                    new AppealDialog(AppealActivity.this, R.style.inputdialogStyle, "", aList, new AppealDialog.OnCloseListener() {
                                        @Override
                                        public void onClick(Dialog dialog, boolean confirm, String name, String code) {
                                            if ("".equals(name)) {
                                                MToast.showToast(AppealActivity.this, "请选择诉求类别");
                                            } else {
                                                appeal_type.setText(name);
                                                dialog.dismiss();
                                            }
                                        }
                                    }).show();
                                } else {
                                    MToast.showToast(AppealActivity.this, appealBean.getMsg());
                                }

                            }

                            @Override
                            public void onFailed(int what, Response<AppealBean> response) {

                            }
                        });


                break;

            case R.id.appeal_bumen:
                new CommomDialog(AppealActivity.this, R.style.inputdialogStyle, "", bmlist, new CommomDialog.OnCloseListener() {
                    @Override
                    public void onClick(final Dialog dialog, List<Choose_BM> bmList, boolean confirm) {
                        String s = "";
                        List list = new ArrayList();
                        //初始化dialog
                        for (int i = 0; i < bmList.size(); i++) {
                            if (bmList.get(i).isSelect()) {
                                list.add(bmList.get(i).getDepName());
                            }
                        }
                        if (list.size() == 0) {
                            MToast.showToast(AppealActivity.this, "请选择部门");
                        } else {
                            for (int i = 0; i < list.size(); i++) {
                                s += list.get(i) + ",";
                            }
                            s = s.substring(0, s.length() - 1);
                            appeal_bumen.setText(s);
                        }
                        dialog.dismiss();
                    }
                }).show();
                break;

            //提交按钮
            case R.id.sb_confirm:
                final String name = appeal_name.getText().toString();
                final String type = appeal_type.getText().toString();
                final String bumen = appeal_bumen.getText().toString();
                final String dis = order_content.getText().toString();

                if (dis.equals("")) {
                    MToast.showToast(AppealActivity.this, "诉求内容不为空");
                    return;
                }
                if ("".equals(name)) {
                    MToast.showToast(AppealActivity.this, "企业名称不为空");
                    return;
                }
//                if ("".equals(type) || "请选择".equals(type)) {
//                    MToast.showToast(AppealActivity.this, "诉求类别不为空");
//                    return;
//                }
                if ("".equals(bumen) || "请选择".equals(bumen)) {
                    MToast.showToast(AppealActivity.this, "部门不为空");
                    return;
                }
                if (url1 == "") {
                    MToast.showToast(AppealActivity.this, "请上传图片");
                    return;
                }

                new SureDiagle(AppealActivity.this, R.style.inputdialogStyle, "", new SureDiagle.OnCloseListener() {
                    @Override
                    public void onClick(final Dialog dialog, boolean confirm) {
                        String url = "http://111.75.240.74:13381/non_public_economy/api/appealApply";
                        MHttp.<Result>create(AppealActivity.this).setUrl(url)
                                .addParams("enterpriseUuid", uuid)
                                .addParams("enterpriseEname", UserXx)
                                .addParams("enterpriseRegion", region)
                                .addParams("enterpriseRegionName", regionName)
                                .addParams("appealType", "1")
                                .addParams("appealTypeName", type)
                                .addParams("appealRegistType", "0")
                                .addParams("appealState", "0")
                                .addParams("isSb", "0")
                                .addParams("complain", "0")
                                .addParams("intentDep", bumen)
                                .addParams("appealImage", url1) //图片地址
                                .addParams("accessToken", accesstoken)
                                .addParams("appealContent", dis)//诉求
                                .execute(new MResponseListener<Result>() {

                                    @Override
                                    public void onSuccess(int what, Result result) {
                                        if (result.isSuccess()) {
                                            //     MToast.showToast(AppealActivity.this, result.getMsg());
                                            dialog.dismiss();
                                            finish();
                                        }else {
                                            MToast.showToast(AppealActivity.this,result.getMsg());
                                            dialog.dismiss();
                                            finish();
                                        }

                                    }

                                    @Override
                                    public void onFailed(int what, Response<Result> response) {

                                    }
                                });


                    }
                }).show();
                break;
            default:
                break;
        }
    }


    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    private void initWidget() {
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);

        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                /**
                                 * 0.4.7 目前直接调起相机不支持裁剪，如果开启裁剪后不会返回图片，请注意，后续版本会解决
                                 *
                                 * 但是当前直接依赖的版本已经解决，考虑到版本改动很少，所以这次没有上传到远程仓库
                                 *
                                 * 如果实在有所需要，请直接下载源码引用。
                                 */
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                                Intent intent = new Intent(AppealActivity.this, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                                Intent intent1 = new Intent(AppealActivity.this, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                break;
                            default:
                                break;
                        }

                    }
                }, names);


                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    ArrayList<ImageItem> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                    List<String> list = new ArrayList<>();
                    for (ImageItem item : selImageList) {
                        list.add(item.path);
                    }
                    upload(list);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);

                }
            }
        }
    }

    //上传
    private void upload(List paths) {
        MUpload.newBuilder(this).setUrl("http://111.75.240.74:13381/non_public_economy/api/uploadList")
                .setPaths("fileList", paths)
                .setNeedCompress(true)
                .execute(new UploadCallBack() {
                    @Override
                    public void onSuccess(String json) {
                        Log.w("json", json);
                        //           url1 = ParseJsonUtil.getStringByKey(json, "url");
                        List<UploadBean> up = ParseJsonUtil.getBeanList(json, UploadBean.class);
                        for (UploadBean uploadBean : up) {
                            url1 += uploadBean.getUrl() + ",";
                        }
                        Log.w("uuuuu",url1);
                    }

                });
    }

}

